package com.sigmatrix.h5.web.dealer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sigmatrix.h5.entity.Enterprise;
import com.sigmatrix.h5.service.EnterpriseService;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.web.Result;
import com.sigmatrix.h5.web.mode.Login;
import com.sigmatrix.sc.jdbc.common.lang.Session;

/**
 * 
 *@ClassName: LoginInterceptor
 *@Description: 获取企业拦截器
 *@author MH
 *@date 2017年11月7日 上午10:24:53
 */
@Component("crmLoginInterceptor")
public class DealerInterceptor implements HandlerInterceptor{
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private EnterpriseService enterpriseService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		String basicModuleEseId = request.getParameter("eseId");
		if(CommonUtils.isEmpty(basicModuleEseId)){
			logger.info(String.format("%s 返回结果:eseId不能为空", request.getRequestURI()));
			response.getWriter().printf(Result.error("eseId不能为空").toString());
			return false;
		}
		if(!CommonUtils.isNumber(basicModuleEseId)){
			logger.info(String.format("%s 返回结果:eseId不是有效数字;参数：[%s]", request.getRequestURI(),basicModuleEseId));
			response.getWriter().printf(Result.error("eseId不是有效数字").toString());
			return false;
			
		}
		Enterprise enterprise = enterpriseService.findByBasicModuleId(Integer.valueOf(basicModuleEseId));
		if(CommonUtils.isEmpty(enterprise)){
			logger.info(String.format("%s 返回结果:eseId不是有效数字;参数：[%s]", request.getRequestURI(),basicModuleEseId));
			response.getWriter().printf(Result.error("eseId不正确,没有查询到企业").toString());
			return false;
		}
		Login login = new Login();
		login.setTablePreffix(enterprise.getCode());
		login.setBasicModuleEseId(enterprise.getBasicModuleId());
		login.setEseCode(enterprise.getCode());
		login.setEseId(enterprise.getId());
		Session.set(login);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		Session.clear();
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		
	}


}
